﻿using java.security.interfaces;
using jieyi.tools.algorithmic;
using jieyi.tools.util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ToolsFromJY
{
    /// <summary>
    /// Sha1WithRSA工具类
    /// </summary>
    public class Sha1WithRSAHelper
    {

        public static bool Sign(string strToSign, out string strAfterSign)
        {
            return Sha1WithRSAHelper.Sign(RSAParams.modulus,RSAParams.exponentPri,RSAParams.exponentPub,strToSign, out strAfterSign);
        }

        /// <summary>
        /// 签名，如果签名发生异常，则返回false且strAfterSign字段填充异常信息
        /// </summary>
        /// <param name="modulus">公钥系数</param>
        /// <param name="exponentPri">私钥系数</param>
        /// <param name="exponentPub">指数大小</param>
        /// <param name="strToSign">待签名字符串</param>
        /// <param name="strAfterSign">签名结果，方法内赋值</param>
        /// <returns></returns>
        public static bool Sign(string modulus,string exponentPri, string exponentPub,string strToSign,out string strAfterSign)
        {
            strAfterSign = "";
            bool isSuccess = true;
            try
            {                
                RSAPublicKey rsaPublicKey = RSAUtil.loadPublicKey(modulus, exponentPub, 16);
                RSAPrivateKey rsaPrivateKey = RSAUtil.loadPrivateKey(modulus, exponentPri, 16);
                strAfterSign = StringUtil.bytesToHexString(SignatureUtil.signature(strToSign, "UTF-8", rsaPrivateKey, ""));
                strAfterSign = strAfterSign.ToUpper();
            }
            catch (Exception ex)
            {
                //String strTmp = ex.ToString();
                //Console.WriteLine(strTmp);
                strAfterSign = ex.ToString();
                isSuccess = false;
            }
            return isSuccess;
        }

        /// <summary>
        /// 验签
        /// </summary>
        /// <param name="modulus">公钥系数</param>
        /// <param name="exponentPri">私钥系数</param>
        /// <param name="exponentPub">指数大小</param>
        /// <param name="strToSign">原始串</param>
        /// <param name="strAfterSign">签名串</param>
        /// <returns></returns>
        public static bool VerifySign(string modulus, string exponentPri, string exponentPub, string strToSign, string strAfterSign)
        {
            bool check = false;
            try
            {                
                RSAPublicKey rsaPublicKey = RSAUtil.loadPublicKey(modulus, exponentPub, 16);
                RSAPrivateKey rsaPrivateKey = RSAUtil.loadPrivateKey(modulus, exponentPri, 16);
                check = SignatureUtil.signVerified(strToSign, "UTF-8", StringUtil.hexStringToBytes(strAfterSign), rsaPublicKey, "");
            }
            catch (Exception ex)
            {
                String strTmp = ex.ToString();
                Console.WriteLine(strTmp);
                check = false;
            }
            return check;
        }
    }
}
